package com.jone.bang;


import java.util.List;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

import com.jone.bang.db.ConfigCenter;
import com.jone.bang.model.WordItem;
import com.jone.bang.service.DownloadService;
import com.jone.bang.util.Constant;

public class BangWidget extends AppWidgetProvider {
		
	private static DownloadService downloadService;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];
            Log.i("ID", ""+i+":"+appWidgetId);
            updateAppWidget(context, appWidgetManager,appWidgetId);
        }
       
	}

	public static void updateAppWidget(Context context,
			AppWidgetManager appWidgetManager,int appWidgetId) {
		if(downloadService == null){
			downloadService = new DownloadService(context);
		}
		List<WordItem> list = downloadService.getList(Constant.TOP_SEARCH_TODAY);
		RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.my_widget);
		
		if(list != null && !list.isEmpty()){
			views.setTextViewText(R.id.top1, list.get(0).getName());
			views.setTextViewText(R.id.top2, list.get(1).getName());
			views.setTextViewText(R.id.top3, list.get(2).getName());
		}
		
		// 创建一个Intent来启动 ExampleActivity
		Intent intent = new Intent(context, HomeActivity.class);
		PendingIntent pendingIntent =PendingIntent.getActivity(context, 0, intent, 0);
		views.setOnClickPendingIntent(R.id.my_widget, pendingIntent);
		
		appWidgetManager.updateAppWidget(appWidgetId, views);
	}
	
	@Override
	public void onEnabled(Context context) {
		ConfigCenter.setValue(context, Constant.KEY_WIDGET_ADDED, true);
		super.onEnabled(context);
	}
	
	@Override
	public void onDisabled(Context context) {
		ConfigCenter.setValue(context, Constant.KEY_WIDGET_ADDED, false);
		super.onDisabled(context);
	}

}
